package com.cry.todo.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cry.core.security.UserDetails;
import com.cry.core.security.UserDetailsImpl;
import com.cry.todo.dao.UserDao;
import com.cry.todo.domain.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao<User> {

	@Override
	public ArrayList<User> loadAll() {
		return (ArrayList<User>) getHibernateTemplate().loadAll(User.class);
	}

	@Override
	public User load(int id) {
		return getHibernateTemplate().load(User.class, id);
	}

	@Override
	public UserDetails loadByUserDetails(String username) {

		List<User> users = getHibernateTemplate().find("FROM User WHERE loginName = ?", username);
		if(users.size() < 1) return null;

		UserDetailsImpl res = new UserDetailsImpl();
		res.setUserId(users.get(0).getId());
		res.setUsername(users.get(0).getLoginName());
		res.setPassword(users.get(0).getPassword());
		res.setAccountNonExpired(true);
		res.setAccountNonLocked(true);
		res.setCredentialsNonExpired(true);
		res.setEnabled(true);
		
		res.setAuthorities(new ArrayList<GrantedAuthority>());
		res.getAuthorities().add(new GrantedAuthorityImpl("ROLE_USER"));
		
		
		return res;
	}

}
